{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Generate out-of-sample predictions with LightGBM and CatBoost"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Imports & Settings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import warnings\n",
    "warnings.filterwarnings('ignore')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-11-09T16:12:33.669796Z",
     "start_time": "2018-11-09T16:12:33.468906Z"
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "from time import time\n",
    "import sys, os\n",
    "from pathlib import Path\n",
    "\n",
    "import pandas as pd\n",
    "from scipy.stats import spearman\n",
    "\n",
    "import lightgbm as lgb\n",
    "from catboost import Pool\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "sys.path.insert(1, os.path.join(sys.path[0], '..'))\n",
    "from utils import MultipleTimeSeriesCV"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-11-09T16:12:33.673698Z",
     "start_time": "2018-11-09T16:12:33.671186Z"
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "sns.set_style('whitegrid')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "YEAR = 252\n",
    "idx = pd.IndexSlice"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "scope_params = ['lookahead', 'train_length', 'test_length']\n",
    "daily_ic_metrics = ['daily_ic_mean', 'daily_ic_mean_n', 'daily_ic_median', 'daily_ic_median_n']\n",
    "lgb_train_params = ['learning_rate', 'num_leaves', 'feature_fraction', 'min_data_in_leaf']\n",
    "catboost_train_params = ['max_depth', 'min_child_samples']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Generate LightGBM predictions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Model Configuration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "base_params = dict(boosting='gbdt',\n",
    "                   objective='regression',\n",
    "                   verbose=-1)\n",
    "\n",
    "categoricals = ['year', 'month', 'sector', 'weekday']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "lookahead = 1\n",
    "store = Path('data/predictions.h5')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Get Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = pd.read_hdf('data/data.h5', 'model_data').sort_index()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "labels = sorted(data.filter(like='_fwd').columns)\n",
    "features = data.columns.difference(labels).tolist()\n",
    "label = f'r{lookahead:02}_fwd'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = data.loc[idx[:, '2010':], features + [label]].dropna()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for feature in categoricals:\n",
    "    data[feature] = pd.factorize(data[feature], sort=True)[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "lgb_data = lgb.Dataset(data=data[features],\n",
    "                       label=data[label],\n",
    "                       categorical_feature=categoricals,\n",
    "                       free_raw_data=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Generate predictions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "lgb_ic = pd.read_hdf('data/model_tuning.h5', 'lgb/ic')\n",
    "lgb_ic_avg = pd.read_hdf('data/model_tuning.h5', 'lgb/ic_avg')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_lgb_params(data, t=5, best=0):\n",
    "    param_cols = scope_params[1:] + lgb_train_params + ['boost_rounds']\n",
    "    df = data[data.lookahead==t].sort_values('ic', ascending=False).iloc[best]\n",
    "    return df.loc[param_cols]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "for position in range(10):\n",
    "    params = get_lgb_params(daily_ic_avg,\n",
    "                    t=lookahead,\n",
    "                    best=position)\n",
    "    \n",
    "    params = params.to_dict()\n",
    "    \n",
    "    for p in ['min_data_in_leaf', 'num_leaves']:\n",
    "        params[p] = int(params[p])\n",
    "    train_length = int(params.pop('train_length'))\n",
    "    test_length = int(params.pop('test_length'))\n",
    "    num_boost_round = int(params.pop('boost_rounds'))\n",
    "    params.update(base_params)\n",
    "\n",
    "    print(f'\\nPosition: {position:02}')\n",
    "    \n",
    "    # 1-year out-of-sample period\n",
    "    n_splits = int(YEAR / test_length)\n",
    "    cv = MultipleTimeSeriesCV(n_splits=n_splits,\n",
    "                              test_period_length=test_length,\n",
    "                              lookahead=lookahead,\n",
    "                              train_period_length=train_length)\n",
    "\n",
    "    predictions = []\n",
    "    start = time()\n",
    "    for i, (train_idx, test_idx) in enumerate(cv.split(X=data), 1):\n",
    "        print(i, end=' ', flush=True)\n",
    "        lgb_train = lgb_data.subset(train_idx.tolist()).construct()\n",
    "\n",
    "        model = lgb.train(params=params,\n",
    "                          train_set=lgb_train,\n",
    "                          num_boost_round=num_boost_round,\n",
    "                          verbose_eval=False)\n",
    "\n",
    "        test_set = data.iloc[test_idx, :]\n",
    "        y_test = test_set.loc[:, label].to_frame('y_test')\n",
    "        y_pred = model.predict(test_set.loc[:, model.feature_name()])\n",
    "        predictions.append(y_test.assign(prediction=y_pred))\n",
    "\n",
    "    if position == 0:\n",
    "        test_predictions = (pd.concat(predictions)\n",
    "                            .rename(columns={'prediction': position}))\n",
    "    else:\n",
    "        test_predictions[position] = pd.concat(predictions).prediction\n",
    "\n",
    "by_day = test_predictions.groupby(level='date')\n",
    "for position in range(10):\n",
    "    if position == 0:\n",
    "        ic_by_day = by_day.apply(lambda x: spearmanr(x.y_test, x[position])[0]).to_frame()\n",
    "    else:\n",
    "        ic_by_day[position] = by_day.apply(lambda x: spearmanr(x.y_test, x[position])[0])\n",
    "print(ic_by_day.describe())\n",
    "test_predictions.to_hdf(store, f'lgb/test/{lookahead:02}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Generate CatBoost predictions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Model Configuration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "lookahead = 1\n",
    "store = Path('data/predictions.h5')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Get Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = pd.read_hdf('data/data.h5', 'model_data').sort_index()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "labels = sorted(data.filter(like='_fwd').columns)\n",
    "features = data.columns.difference(labels).tolist()\n",
    "label = f'r{lookahead:02}_fwd'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = data.loc[idx[:, '2010':], features + [label]].dropna()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for feature in categoricals:\n",
    "    data[feature] = pd.factorize(data[feature], sort=True)[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "catboost_data = Pool(label=outcome_data[label],\n",
    "                     data=outcome_data.drop(label, axis=1),\n",
    "                     cat_features=cat_cols_idx)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Generate predictions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "catboost_ic = pd.read_hdf('data/model_tuning.h5', 'catboost/ic')\n",
    "catboost_ic_avg = pd.read_hdf('data/model_tuning.h5', 'catboost_ic/ic_avg')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_cb_params(data, t=5, best=0):\n",
    "    param_cols = scope_params[1:] + catboost_train_params + ['boost_rounds']\n",
    "    df = data[data.lookahead==t].sort_values('ic', ascending=False).iloc[best]\n",
    "    return df.loc[param_cols]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "for position in range(10):\n",
    "    params = get_cb_params(catboost_ic_avg,\n",
    "                    t=lookahead,\n",
    "                    best=position)\n",
    "    \n",
    "    params = params.to_dict()\n",
    "    \n",
    "    for p in ['max_deptn', 'min_child_samples']:\n",
    "        params[p] = int(params[p])\n",
    "    train_length = int(params.pop('train_length'))\n",
    "    test_length = int(params.pop('test_length'))\n",
    "    num_boost_round = int(params.pop('boost_rounds'))\n",
    "    params['task_type'] = 'GPU'\n",
    "\n",
    "    print(f'\\nPosition: {position:02}')\n",
    "    \n",
    "    # 1-year out-of-sample period\n",
    "    n_splits = int(YEAR / test_length)\n",
    "    cv = MultipleTimeSeriesCV(n_splits=n_splits,\n",
    "                              test_period_length=test_length,\n",
    "                              lookahead=lookahead,\n",
    "                              train_period_length=train_length)\n",
    "\n",
    "    predictions = []\n",
    "    start = time()\n",
    "    for i, (train_idx, test_idx) in enumerate(cv.split(X=data), 1):\n",
    "        print(i, end=' ', flush=True)\n",
    "        train_set = catboost_data.slice(train_idx.tolist())\n",
    "\n",
    "        model = CatBoostRegressor(**params)\n",
    "        model.fit(X=train_set,\n",
    "                  verbose_eval=False)\n",
    "\n",
    "        test_set = data.iloc[test_idx, :]\n",
    "        y_test = test_set.loc[:, label].to_frame('y_test')\n",
    "        y_pred = model.predict(test_set.loc[:, model.feature_name()])\n",
    "        predictions.append(y_test.assign(prediction=y_pred))\n",
    "\n",
    "    if position == 0:\n",
    "        test_predictions = (pd.concat(predictions)\n",
    "                            .rename(columns={'prediction': position}))\n",
    "    else:\n",
    "        test_predictions[position] = pd.concat(predictions).prediction\n",
    "\n",
    "by_day = test_predictions.groupby(level='date')\n",
    "for position in range(10):\n",
    "    if position == 0:\n",
    "        ic_by_day = by_day.apply(lambda x: spearmanr(x.y_test, x[position])[0]).to_frame()\n",
    "    else:\n",
    "        ic_by_day[position] = by_day.apply(lambda x: spearmanr(x.y_test, x[position])[0])\n",
    "print(ic_by_day.describe())\n",
    "test_predictions.to_hdf(store, f'catboost/test/{lookahead:02}')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.7"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": true,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "301.861px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
